package com.runjian.rundo.bmp.kernel.common.logback.core;

import org.slf4j.helpers.MessageFormatter;

import com.alibaba.fastjson2.JSON;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * 日志输出参数JSON格式化类
 *
 * @author Hollis
 */
public class ArgumentJsonFormatLayout extends MessageConverter {

    @Override
    public String convert(ILoggingEvent event) {
        try {
            final int len = event.getArgumentArray().length;
            final Object[] argArray = event.getArgumentArray();
            for (int i = 0; i < len; i++) {
                Object arg = argArray[i];
                if (!(arg instanceof String)) {
                    argArray[i] = JSON.toJSONString(arg);
                }
            }

            return MessageFormatter.arrayFormat(event.getMessage(), argArray).getMessage();
        } catch (Exception e) {
            return event.getMessage();
        }
    }
}
